# apps/questions/models.py
from django.db import models
from django.utils.translation import gettext_lazy as _
from apps.subjects.models import Subject
from apps.tenants.models import Tenant
from apps.users.models import QBUser
from apps.tags.models import Tag


class Question(models.Model):
    """
    试题主表
    对应数据库表: qb_questions
    """
    QUESTION_TYPE_CHOICES = [
        ('single', _('单选题')),
        ('multiple', _('多选题')),
        ('true_false', _('判断题')),
        ('short_answer', _('简答题')),
        ('fill_blank', _('填空题')),
    ]

    STATUS_CHOICES = [
        ('draft', _('草稿')),
        ('reviewing', _('审核中')),
        ('published', _('已发布')),
        ('disabled', _('已禁用')),
    ]

    # 基本信息
    title = models.TextField(_('题干'), help_text=_('支持HTML或富文本'))
    question_type = models.CharField(_('题型'), max_length=20, choices=QUESTION_TYPE_CHOICES)
    difficulty = models.PositiveSmallIntegerField(_('难度'), default=3, help_text=_('1-5，1为最简单'))
    analysis = models.TextField(_('题目解析'), null=True, blank=True)
    reference = models.CharField(_('来源/出处'), max_length=200, null=True, blank=True, help_text=_('如：教材P10'))
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE, verbose_name=_('所属学科'))
    creator = models.ForeignKey(QBUser, on_delete=models.CASCADE, verbose_name=_('创建人'))
    status = models.CharField(_('状态'), max_length=20, choices=STATUS_CHOICES, default='draft')

    # 统计字段
    view_count = models.PositiveIntegerField(_('浏览次数'), default=0)
    use_count = models.PositiveIntegerField(_('被组卷使用次数'), default=0)

    # 时间戳
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)
    updated_at = models.DateTimeField(_('更新时间'), auto_now=True)

    tags = models.ManyToManyField(
        'tags.Tag',
        through='questions.QuestionTag',
        related_name='questions'
    )

    tenant = models.ForeignKey(Tenant, on_delete=models.CASCADE, null=True, db_index=True, verbose_name="租户")

    class Meta:
        db_table = 'qb_questions'
        verbose_name = _('试题')
        verbose_name_plural = _('试题')
        indexes = [
            models.Index(fields=['tenant'], name='idx_question_tenant'),
            models.Index(fields=['subject'], name='idx_subject_id'),
            models.Index(fields=['creator'], name='idx_creator_id'),
            models.Index(fields=['question_type'], name='idx_type'),
            models.Index(fields=['difficulty'], name='idx_difficulty'),
            models.Index(fields=['status'], name='idx_status'),
            models.Index(fields=['-created_at'], name='idx_created_at'),
        ]

    def __str__(self):
        return f"[{self.get_question_type_display()}] {self.title[:50]}{'...' if len(self.title) > 50 else ''}"


class QuestionTag(models.Model):
    """
    试题-标签关联表（多对多关系）
    对应数据库表: qb_question_tags
    """
    question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name=_('试题'))
    tag = models.ForeignKey(Tag, on_delete=models.CASCADE, verbose_name=_('标签'))
    created_at = models.DateTimeField(_('创建时间'), auto_now_add=True)

    class Meta:
        db_table = 'qb_question_tags'
        unique_together = ('question', 'tag')
        verbose_name = _('试题-标签关联')
        verbose_name_plural = _('试题-标签关联')
        indexes = [
            models.Index(fields=['question']),
            models.Index(fields=['tag']),
        ]

    def __str__(self):
        return f"{self.question.title[:30]} - {self.tag.name}"